package com.xs.smc.service;

import com.xs.smc.entity.Order;
import com.xs.smc.enums.OrderEvent;
import com.xs.smc.enums.OrderStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @Autowired
    private StateMachine<OrderStatus, OrderEvent> stateMachine;

    /**
     * 订单流转
     */
    public boolean processOrder(Order order, OrderEvent event) {
        // 先重置状态机到当前订单状态
        stateMachine.stop();
        stateMachine.getStateMachineAccessor().doWithAllRegions(access -> {
            access.resetStateMachine(new DefaultStateMachineContext<>(order.getStatus(), null, null, null));
        });
        stateMachine.start();

        // 发送事件
        Message<OrderEvent> message = MessageBuilder
                .withPayload(event)
                .setHeader("order", order)
                .build();
        boolean success = stateMachine.sendEvent(message);

        // 状态同步到订单对象
        if (success) {
            order.setStatus(stateMachine.getState().getId());
        }
        return success;
    }

    public Order getOrderById(Long id) {
        // 伪代码， 实际查询order
        return new Order(id);
    }
}